"""Models.py
"""
from datetime import datetime#, timedelta
#import sys
#import re
#import os

from django.contrib.gis.db import models
from django.contrib.auth.models import User

import utils
# Create your models here.


class Point(models.Model):
    """Single point on the level"""
    x = models.FloatField(help_text="This is the left to right value")
    y = models.FloatField(help_text="This is the up to down value")
    level = models.ForeignKey("Level")

class Color(models.Model):
    """Color used for ground and sky"""
    r = models.PositiveIntegerField(default=255, help_text='Red')
    g = models.PositiveIntegerField(default=255, help_text='Green')
    b = models.PositiveIntegerField(default=255, help_text='Blue')
    a = models.PositiveIntegerField(default=255, help_text='Alpha')

    @property
    def hex_str(self):
        return utils.rgb_to_hex((self.r, self.g, self.b))

class Level(models.Model):
    """Level"""
    display_name = models.CharField(max_length=128, null=True, default='')
    name = models.CharField(max_length=128, unique=True)
    hill_color_base = models.ForeignKey(Color, related_name='+')
    hill_color_alt = models.ForeignKey(Color, related_name='+', null=True, help_text="Computer if not given")
    sky_color = models.ForeignKey(Color, related_name='+')
    sequence = models.PositiveIntegerField(db_index=True, help_text="The sequence the level falls, the lower the earlier")
    active = models.BooleanField(default=False, help_text="Set this to true in order to have the level become active")
    gravity_factor_y = models.FloatField(default=9.8, help_text='Gravity Downward')
    gravity_factor_x = models.FloatField(default=0, help_text="Gravity Foward, generally 0")
    when_created = models.DateTimeField(default=datetime.utcnow)
    creator = models.ForeignKey(User, null=True, blank=True)
    time_to_complete = models.PositiveIntegerField(null=True)

    @property
    def point_count(self):
        return Point.objects.filter(level=self).count()

    @property
    def points(self):
        return Point.objects.filter(level=self).order_by('x')

    @property
    def creator_username(self):
        return self.creator.username

